﻿using Ldt.DataEngine.DataFlowParse.Model;
using Ldt.InformationUnit.Common;
using LdtDataEngin.ModuleDetail.BaseModule.Optimization;
using LdtDataEngin.ModuleDetail.OptimizationModule.StageOptimization;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.ConfigXmlLoad;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.Collection;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.OptimizationModule.CaseCauseMergeOpt
{
    public class CaseCauseMergeOpt : OptimizationBase
    {
        /// <summary>
        /// 合并后要素配置
        /// </summary>
        private OptimizeConfig stageoptimizeConfig = new OptimizeConfig();

        public CaseCauseMergeOpt(DataContext context, string moduleName)
        {
            dataContext = context;
            this.ModuleName = moduleName;
            var configModel = base.dataContext.DataLayerSys.GetConfigModel(moduleName);
            if (configModel.ConfigDetail != null)
            {
                foreach (ConfigModel item in configModel.ConfigDetail)
                {
                    if (item.ExecuteType == "xml_var" && item.Code == "causeoptimize")
                    {
                        if (!string.IsNullOrWhiteSpace(item.FilePath))
                        {
                            string url = item.FilePath.Replace("{casetype}", dataContext.DataLayerOpt.CaseType).Replace("{causecode}", dataContext.DataLayerAns.CaseCausesList[0].CC_ID).ToLower().Replace(" ", "");

                            Dictionary<string, string> dicElement = new Dictionary<string, string>();
                            dicElement.Add("fileFullName", url);
                            string elementMessage = WebUtil.DoGet(ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");
                            dynamic elementcofig = JsonConvert.DeserializeObject<dynamic>(elementMessage);
                            if (elementcofig.result.code.ToString() == "1")
                            {
                                string elementcofigstr = elementcofig.body;
                                stageoptimizeConfig = XmlUtility.DeserializeToObject<OptimizeConfig>(elementcofigstr);
                            }
                        }
                    }
                }
            }
           
        }
        /// <summary>
        /// 执行合并后要素优选
        /// </summary>
        /// <param name="stageOpConfig"></param>
        public void MergeOp()
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() {dataContext=dataContext };
            //上次优选结果数据
            List<DataModel> onedataModelList = dataContext.DataLayerOpt.MergeElmentDataModelList;
            //本次分析结果数据
            List<DataModel> twodataModelList = dataContext.DataLayerAns.MergeElmentDataModelList;
            //结果数据
            List<DataModel> resultdataModelList = new List<DataModel>();

            if (onedataModelList != null && onedataModelList.Count > 0 && twodataModelList != null && twodataModelList.Count > 0)
            {
                Optimization(onedataModelList, twodataModelList);
                resultdataModelList = onedataModelList;
            }
            else if ((twodataModelList != null && twodataModelList.Count > 0) && (onedataModelList == null || onedataModelList.Count == 0))
            {
                resultdataModelList = onedataModelList;
            }
            resultdataModelList = resultdataModelList.Where(a => a.State != "2").ToList();
            //嵌入合并后要素位置
            DOCLocationModel locationModel = new DOCLocationModel();
            locationModel = base.dataContext.DataLayerSys.locationModelList.FirstOrDefault(a => a.DocType.ToLower() == "currentdata");
            xmlUtilCommon.CaseNodeUpdate(base.dataContext.DataLayerOpt.SourdatModleList, locationModel.MergeElmentPath);
            string prentID = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", locationModel.MergeElmentPath).ID;
            try
            {
                DataModel dataModelRoot = XmlUtility.ConditionFirstOrDefaultDataModel(base.dataContext.DataLayerOpt.SourdatModleList, "", locationModel.MergeElmentPath);
                if (dataModelRoot != null)
                {
                    List<DataModel> dataModelRovmeList = xmlUtilCommon.SubordinateDataModelList(base.dataContext.DataLayerOpt.SourdatModleList, dataModelRoot);
                    if (dataModelRovmeList.Count > 0)
                    {
                        foreach (var item in base.dataContext.DataLayerOpt.SourdatModleList.Where(a => a.ParentId == prentID))
                        {
                            base.dataContext.DataLayerOpt.SourdatModleList.Remove(item);

                        }
                    }

                }

            }
            catch (Exception elemtex)
            {

                dataContext.InteractiveShow.LogShow("\r\n----------★清除数据错误★----------\r\n" + elemtex.ToString(), LogMessageType.Error);
            }

            resultdataModelList.FirstOrDefault(a => a.ParentId == "").ParentId = prentID;
            base.dataContext.DataLayerOpt.SourdatModleList.AddRange(resultdataModelList);
            XmlDocument xmlDocument = XmlUtility.DataModelByXml(base.dataContext.DataLayerOpt.SourdatModleList);
            base.dataContext.DataLayerOpt.OptimizationXml = xmlDocument;
        }


        /// <summary>
        /// 优选功能
        /// </summary>
        /// <param name="stageOpConfig">配置文件</param>
        /// <param name="onedataModelList">基础合并要素</param>
        /// <param name="twodataModelList">分析结果合并要素</param>
        public void Optimization(List<DataModel> onedataModelList, List<DataModel> twodataModelList)
        {
            StageOptimizationClass stageOptimizationClass = new StageOptimizationClass() { dataContext = dataContext,MergeOp=true };
            stageOptimizationClass.CaseElmentOptimization(twodataModelList, "", onedataModelList, stageoptimizeConfig);
        }
    }
}
